package com.npjscg.medicalpro.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.npjscg.medicalpro.controller.dto.UserDTO;
import com.npjscg.medicalpro.entity.User;
import com.npjscg.medicalpro.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtils {

    @Autowired
    private static IUserService userService;

    public static String genToken(int userId, String sign) {
        return JWT.create().withAudience(String.valueOf(userId)) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }


    //验证token
    public static boolean verify(String token, String password){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(password)).build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("userid: " + jwt.getClaim("userid").asString());
            System.out.println("过期时间：      " + jwt.getExpiresAt());
            return true;
        } catch (Exception e){
            return false;
        }
    }




    public static void main(String[] args) {
        String root = genToken(1,"123");
        System.out.println(root);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(1);
        userDTO.setPassword("123");
        userDTO.setToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjU2MDg2MjM2fQ.hNkL28dvKWj0fG1y84cgtgOEdlp9qdwzjsryENa6KEs");



    }


}
